<?php
class BooksController extends AppController {
	var $ver = "_v2";
	var $name = "Books";
	var $paginate = array ('Book' => array ('limit' => 10, 'joins' => array (array ('table' => 'books_series_link', 'alias' => 'bs', 'type' => 'left', 'conditions' => array ('bs.book=book.id' ) ) ), 'order' => array ('Book.id' => 'desc' ), 'contain' => array ('Author', 'Data', 'Comment', 'Series' ) ) );
	var $helpers = array ('Html', 'Text', 'Time', 'Image' );
	
	var $scaffold = 'admin';
	
		
	public $components = array('Session','Email',
    'Auth'=> array(
        'authenticate' => array(
            'Form' => array(
                'fields' => array('username' => 'email','password'=>'password')
            )
        )
    )
);
	
	function index() {
		$this->layout = 'duxiang';
		//$this->view = "index" . $this->ver;
//		if ($this->Session->check ( 'me' )) {
//			$loginUser = $this->Session->read ( 'me' );
//			$this->set ( 'loginUser', $loginUser ['name'] );
//			$this->set ( 'userRole', $this->Auth->user ( 'role' ) );
//			$this->set('isLogin',true);
//		}
		//echo $this->Auth->user ( 'email' );
		$this->loadModel ( 'Serie' );
		$this->loadModel ( 'Stat' );
		$this->loadModel ( 'Download' );
		$this->loadModel('Note');
		
		$this->set ( 'title_for_layout', '首页' );
		$this->set ( 'series', $this->Serie->find ( 'all' ) );
		
		$this->set ( 'new_books', $this->Book->find ( 'all', array ('order' => array ('Book.id DESC' ), 'limit' => 5 ) ) );
		
		$new_downloads = $this->Download->find('all',array('order'=>array('Download.id DESC' ), 'limit'=>5 ) );
		for( $i = 0; $i < count($new_downloads); $i++ ){
			$new_downloads[$i]['Book'] = $this->Book->findById($new_downloads[$i]['Download']['book'] );
		}
		
		$notes = $this->Note->find( 'all', array( 
			'order'=>array( 'Note.id DESC' ),
			'limit'=>5 ) );
		for( $i = 0; $i < count($notes); $i++ ){
			$notes[$i]['Book'] = $this->Book->findById($notes[$i]['Note']['book'] );
		}
		$this->set('notes', $notes);
		
		$this->set('new_downloads',$new_downloads);
	}
	
	
	
	function serie($id = 0) {
		$this->loadModel ( 'Serie' );
		$this->layout = 'duxiang';
		
		
		$this->set ( 'series', $this->Serie->find ( 'all' ) );
		
		$ser = $this->Serie->find ( 'first', array ('conditions' => 'Serie.id = ' . $id ) );
		if (isset ( $id ) && $id > 0) {
			$this->set ( 'title_for_layout', $ser ["Serie"] ['name'] );
			$this->set ( 'books', $this->paginate ( 'Book', array ('bs.series' => $id ) ) );
		} else
			$this->set ( 'books', $this->paginate ( 'Book' ) );
	}
	
	function view($id = 0) {
		$this->loadModel ( 'Serie' );
		$this->loadModel ( 'Note' );
		$this->layout = 'duxiang';
		
		$this->set ( 'series', $this->Serie->find ( 'all' ) );
		
		$book = $this->Book->findById ( $id );
		$ser = $book ['Series'] [0];
		
		$books_after = $this->Book->query ( "SELECT b.id, b.title, b.sort, b.timestamp, b.pubdate, b.series_index, b.author_sort, b.isbn, b.lccn,b.path, b.flags, b.uuid, b.has_cover,b.last_modified from books as b left join books_series_link as bs on b.id = bs.book where bs.series = " . $ser ['id'] . " and b.id > " . $id . " order by b.id desc limit 3" );
		$books_before = $this->Book->query ( "SELECT b.id, b.title, b.sort, b.timestamp, b.pubdate, b.series_index, b.author_sort, b.isbn, b.lccn,b.path, b.flags, b.uuid, b.has_cover,b.last_modified from books as b left join books_series_link as bs on b.id = bs.book where bs.series = " . $ser ['id'] . " and b.id < " . $id . " order by b.id desc limit 3" );
		$notes = $this->Note->find ( 'all', array ('order' => array ('Note.id DESC' ), 'conditions' => array ('Note.book=' . $id ), 'limit' => 10 ) );
		
		if (isset ( $book )) {
			$this->set ( 'title_for_layout', $book ['Book'] ['title'] . '-' . $ser ['name'] );
			
			$this->set ( 'serie', $ser );
			$this->set ( 'book', $book );
			$this->set ( 'books_after', $books_after );
			$this->set ( 'books_before', $books_before );
			$this->set ( 'notes', $notes );
			
			$this->loadModel ( 'Stat' );
			$stat = $this->Stat->findByBook ( $id );
			if (! isset ( $stat ) || $stat == false) {
				$stat ['Stat'] ['book'] = $id;
				$this->Stat->save ( $stat );
				$stat = $this->Stat->findById($this->Stat->id);
			}
			$this->set ( 'stat', $stat );
			
			if ($this->Session->check ( 'kindle.mail' )) {
				$kindle = explode ( '@', $this->Session->read ( 'kindle.mail' ) );
				$this->set ( 'kindle_name', $kindle [0] );
				$this->set ( 'kindle_domain', $kindle [1] );
			}
			
//			if ($this->Session->check ( 'me' ) && $this->Session->check ( 'last_key.oauth_token' ))
//				$this->set ( 'isLogin', 'true' );
//			else {
//				$this->set ( 'isLogin', 'false' );
//				$this->Session->delete ( 'me' );
//				$this->Session->delete ( 'last_key' );
//			}
		}
	
	}
	
	function doDownload($id, $share_text = NULL, $share_img = NULL) {
		
		//发微博
		if (isset ( $share_text )) {
			$last_key = $this->Session->read ( 'token' );
			$c = new SaeTClientV2( WB_AKEY , WB_SKEY , $last_key['access_token'] );
			
			//如果有图片
			if (isset ( $share_img ))
				$status = $c->upload ( $share_text, $share_img );
			else
				$status = $c->update ( $share_text );
		}
		
		//处理用户下载
		$this->loadModel ( 'Download' );
		
		$download = $this->Download->find ( 'first', array ('conditions' => array ('Download.user' => $this->Auth->user ( 'id' ), 'Download.book' => $id ) ) );
		
		if (! isset ( $download ) || $download == false) {
			$download ['Download'] ['user'] = $this->Auth->user ( 'id' );
			$download ['Download'] ['book'] = $id;
			$download ['Download'] ['timestamp'] = date ( 'Y-m-d H:i:s' );
			if (isset ( $status ['id'] ))
				$download ['Download'] ['weibo_status'] = $status ['id'];
			
			$this->Download->save ( $download );
			
			//处理统计
			$this->loadModel ( 'Stat' );
			$stat = $this->Stat->findByBook ( $id );
			if (! isset ( $stat ) || $stat == false) {
				$stat ['Stat'] ['book'] = $id;
				$stat ['Stat'] ['download_count'] = 1;
				$this->Stat->save ( $stat );
			} else {
				$this->Stat->id = $stat ['Stat'] ['id'];
				$this->Stat->saveField ( 'download_count', $stat ['Stat'] ['download_count'] + 1 );
			}
		}
		
	
	}
	
	function download($id) {
		$this->viewClass = "Media";
		
		$user = $this->Auth->user();
		if( !isset($user))
			$this->redirect ( '/users/sina_login?last_url=/books/view/' . $id );
		
		$this->view = "Media";
		$this->loadModel ( 'Data' );
		$this->loadModel ( 'Download' );
		
		$this->set ( 'post', $_POST );
		$format = strtolower ( $_POST ['format'] );
		
		$book = $this->Book->find ( 'first', array ('conditions' => array ('Book.id' => $id ) ) );
		$data = $this->Data->find ( 'first', array ('conditions' => array ('Data.book' => $id, 'Data.format' => $format ) ) );
		
		$share_text = $_POST ['share_text'];
		
		$param = array ('id' => $data ["Data"] ["name"] . "." . $format, 'name' => $book ['Book'] ['title'].".".$format, 'download' => true, 'extension' => $format, 'mimeType' => array ('azw' => 'application/octet-stream', 'mobi' => 'application/x-mobipocket', 'pdf' => 'application/pdf', 'epub' => 'application/octet-stream' ), 'path' => APP . 'calibre' . DS . $book ['Book'] ['path'] . DS );
		$this->set ( $param );
		
		if ($_POST ['submit'] == '承诺并分享') {
			$share_text .= 'http://book.lupinlin.com/books/view/' . $id;
			$share_img = 'http://book.lupinlin.com/img/pic/' . $book ['Book'] ['id'] . '_300x420_0.jpg';
			$this->doDownload ( $id, $share_text, $share_img );
		} else
			$this->doDownload ( $id );
	}
	
	
	function send_to_kindle($id) {
		$this->layout = 'min';
		

		
		//$user = $this->Auth->user ();
		//没有登录
		//if (! isset ( $user )) {
		//	echo json_encode ( array ('success' => false, 'msg' => 'NO_LOGIN' ) );
		//	return;
		//}
		
		
		$format = strtolower ( $_POST ['format'] );
		$mail = $_POST ['kindle_mail'];
		//echo $mail;
		

		$this->loadModel ( 'Data' );
		$this->loadModel ( 'Queue' );
		$this->loadModel ( 'Kindle' );
		
		$book = $this->Book->find ( 'first', array ('conditions' => array ('Book.id' => $id ) ) );
		$data = $this->Data->find ( 'first', array ('conditions' => array ('Data.book' => $id, 'Data.format' => $format ) ) );
		
		if (intval ( $data ['Data'] ['uncompressed_size'] ) > 20000000) {
			echo '本书大小超过20M, 无法直接发送到Kindle, 请下载后通过数据线传输';
			return;
		}
		
		$d ['Queue'] ['mail'] = $mail;
		$d ['Queue'] ['file'] = APP . 'calibre' . DS . $book ['Book'] ['path'] . DS . $data ['Data'] ['name'] . '.' . strtolower ( $data ['Data'] ['format'] );
		$d ['Queue'] ['title'] = $book ['Book'] ['title'];
		
		$share_text = $_POST ['share_text'];
		
		try {
			$this->Queue->save ( $d );
			
			$user_id = $this->Auth->user ( 'id' );
			$kindle = $this->Kindle->findByUser ( $user_id );
			
			if (! isset ( $kindle ) || $kindle == false) {
				$kindle ['Kindle'] ['user'] = $user_id;
				$kindle ['Kindle'] ['mail'] = $mail;
				$kindle ['Kindle'] ['auto_send'] = 0;
				$this->set ( 'Kindle', $kindle );
				$this->Kindle->save ( $kindle );
			}
		} catch ( Exception $e ) {
			echo json_encode ( array ('success' => false, 'msg' => $e->getMessage () ) );
			return;
		}
		$this->Session->write ( 'kindle.mail', $mail );
		
		if ($_POST ['submit'] == '承诺并分享') {
			$share_text .= 'http://book.lupinlin.com/books/view/' . $id;
			$share_img = 'http://book.lupinlin.com/img/pic/' . $book ['Book'] ['id'] . '_300x420_0.jpg';
			$this->doDownload ( $id, $share_text, $share_img );
		} else
			$this->doDownload ( $id );
		
		echo json_encode ( array ('success' => true, 'msg' => "本书将在10分钟内发往您的Kindle(如果文件很大, 时间可能更长). 您可以继续访问其他页面." ) );
	
	}
	
	function send_to_kindle2() {
		$this->layout = "ajax";
		$id = $_POST ['id'];
		$format = strtolower ( $_POST ['format'] );
		$mail = $_POST ['mail'];
		
		$this->loadModel ( 'Data' );
		
		$book = $this->Book->find ( 'first', array ('conditions' => array ('Book.id' => $id ) ) );
		$data = $this->Data->find ( 'first', array ('conditions' => array ('Data.book' => $id, 'Data.format' => $format ) ) );
		
		$this->Email->smtpOptions = array ('request' => array ('uri' => array ('scheme' => 'https' ) ), 'port' => '465', 'host' => 'smtp.gmail.com', 'username' => 'lupin.lin@gmail.com', 'password' => 'dolly830729' );
		
		$this->Email->delivery = 'smtp';
		$this->Email->to = $mail;
		//$this->Email->bcc = array ('secret@example.com' );
		$this->Email->subject = $book ['Book'] ['title'];
		$this->Email->replyTo = 'lupin.lin@gmail.com';
		$this->Email->from = 'lupin.lin@gmail.com';
		$this->Email->template = 'simple'; // note no '.ctp'    
		//Send as 'html', 'text' or 'both' (default is 'text')    
		$this->Email->sendAs = 'text'; // because we like to send pretty mail    
		//Set view variables as normal    
		//$this->set('User', $User);    //Do not pass any args to send()
		$fileUri = APP . 'calibre' . DS . $book ['Book'] ['path'] . DS . $data ['Data'] ['name'] . '.' . strtolower ( $data ['Data'] ['format'] );
		$this->Email->attachments = array ($fileUri );
		$this->Email->send ();
		echo $this->Email->smtpError;
		echo "发送成功";
	
	}
	
	function beforeFilter() {
		parent::beforeFilter();
		$this->Auth->authorize = 'controller';
		$this->Auth->allow ( '*' );
	
		//$this->Auth->deny ( 'download' );
	}


}